package com.spark.security.handle;

import com.spark.common.core.entity.LoginUser;
import com.spark.common.core.entity.system.SysUser;
import com.spark.common.exception.SparkException;
import com.spark.modules.system.service.ISysPermissionService;
import com.spark.modules.system.service.ISysUserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * 用户验证处理
 *
 * @author LYCHEE
 * @date 2025/2/18 14:44
 */
@Slf4j
@Service
public class UserDetailsServiceImpl implements UserDetailsService {

    @Resource
    private ISysUserService sysUserService;
    @Resource
    private ISysPermissionService sysPermissionService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        SysUser user = sysUserService.getUserByUsername(username);
        if (null == user){
            throw new SparkException("登录用户：" + username + " 不存在");
        }else if (1 == user.getStatus()){
            throw new SparkException("对不起，您的账号：" + username + " 已被禁用");
        }
        return createLoginUser(user);
    }

    public UserDetails createLoginUser(SysUser user){
        return new LoginUser(user.getId(), user.getDeptId(), user, sysPermissionService.getAccessCodes(user.getId()));
    }

}
